package com.qumoyugo.springframework.beans.factory.support;

import cn.hutool.core.util.StrUtil;
import com.qumoyugo.springframework.beans.BeansException;
import com.qumoyugo.springframework.beans.factory.DisposableBean;

import java.lang.reflect.Method;

/**
 * @author Cedric
 * @date 2021/11/25 15:45
 * @description 定义销毁方法适配器
 */
public class DisposableBeanAdapter implements DisposableBean {

    private Object bean;
    private String beanName;
    private String destroyMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, String destroyMethodName) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodName = destroyMethodName;
    }

    @Override
    public void destroy() throws Exception {
        // 1.实现了DisposableBean接口
        if (bean instanceof DisposableBean) {
            ((DisposableBean)bean).destroy();
        }
        // 2.或从配置中读取destroy方法执行
        if (StrUtil.isNotEmpty(destroyMethodName) && !(bean instanceof DisposableBean && "destroy".equals(destroyMethodName))) {
            Method destroyMethod = bean.getClass().getMethod(destroyMethodName);
            if (null == destroyMethod) {
                throw new BeansException("Could not find a destroy method named " + destroyMethodName + "on bean with" + beanName);
            }
            destroyMethod.invoke(bean);
        }
    }
}
